package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.utils.RsaKeyUtil;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.KeyPair;
import java.util.List;

/**
 * 用户业务处理
 **/
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private TransferStationMapper transferStationMapper;

    @Resource
    private ShareFileMapper shareFileMapper;

    @Resource
    private FriendListMapper friendListMapper;

    @Resource
    private FriendApplyMapper friendApplyMapper;

    /**
     * 新增
     */
    @Transactional
    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            user.setPassword(securePassword(Constants.USER_DEFAULT_PASSWORD));
        } else {
            user.setPassword(securePassword(user.getPassword()));
        }
        if (ObjectUtil.isEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        user.setRole(RoleEnum.USER.name());
        userMapper.insert(user);

//        首先查询该用户是否有中转站
        User user1 = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotEmpty(user1)) {
            TransferStation transferStation = transferStationMapper.selectByUserId(user1.getId());
            if (ObjectUtil.isEmpty(transferStation)) {
                transferStation = new TransferStation();
                transferStation.setUserId(user1.getId());
                transferStation.setCurrentSize(new BigDecimal(0));
                transferStation.setMaxSize(new BigDecimal(1024));
                transferStation.setName(user1.getName() + "的中转站");
                transferStationMapper.insert(transferStation);
            }
        }
    }

    /**
     * 删除
     */
    @Transactional
    public void deleteById(Integer id) {
//        删除对应的中转站
        TransferStation transferStation = transferStationMapper.selectByUserId(id);
        if (ObjectUtil.isNotEmpty(transferStation)) {
            transferStationMapper.deleteById(transferStation.getId());
        }
//        删除所有该用户发送和接收的分享文件记录
        ShareFile shareFile = new ShareFile();
        shareFile.setUserId(id);
        List<ShareFile> list = shareFileMapper.selectAll(shareFile);
        for (ShareFile shareFile1 : list) {
            TransferStation transferStation1 = transferStationMapper.selectById(shareFile1.getTransferStationId());
//            更新相应的中转站当前内存
            if (ObjectUtil.isNotEmpty(transferStation1)) {
                transferStation1.setCurrentSize(transferStation1.getCurrentSize().subtract(shareFile1.getCurrentSize()));
                transferStationMapper.updateById(transferStation1);
            }
//            删除分享文件
            shareFileMapper.deleteById(shareFile1.getId());
        }
        shareFile.setUserId(null);
        shareFile.setReceiverId(id);
        List<ShareFile> list1 = shareFileMapper.selectAll(shareFile);
        for (ShareFile shareFile1 : list1) {
//            删除接收文件
            shareFileMapper.deleteById(shareFile1.getId());
        }

//        删除所有该用户发送的好友申请
        List<FriendApply> friendApplies = friendApplyMapper.selectByUserId(id);
        for (FriendApply friendApply : friendApplies) {
            friendApplyMapper.deleteById(friendApply.getId());
        }
//        删除所有申请该用户为好友的好友申请
        List<FriendApply> friendApplies1 = friendApplyMapper.selectByApplyUserId(id);
        for (FriendApply friendApply : friendApplies1) {
            friendApplyMapper.deleteById(friendApply.getId());
        }

//        删除所有关于该用户的好友列表信息
        List<FriendList> friendLists = friendListMapper.selectByUserId(id);
        for (FriendList friendList : friendLists) {
            friendListMapper.deleteById(friendList.getId());
        }
        List<FriendList> friendLists1 = friendListMapper.selectByFriendId(id);
        for (FriendList friendList : friendLists1) {
            friendListMapper.deleteById(friendList.getId());
        }
//        删除
        userMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(User user) {
        userMapper.updateById(user);
    }

    /**
     * 根据ID查询
     */
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    /**
     * 分页查询
     */
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    /**
     * 注册
     */
    public void register(Account account)throws Exception {
        User user = new User();
        user.setUsername(account.getUsername());
        user.setPassword(account.getPassword());
        user.setPasswordProblem(account.getPasswordProblem());
        user.setPasswordReply(account.getPasswordReply());

        // 生成RSA密钥对
        KeyPair keyPair = RsaKeyUtil.generateRsaKeyPair();
        String publicKey = RsaKeyUtil.encodePublicKey(keyPair.getPublic());
        String privateKey = RsaKeyUtil.encodePrivateKey(keyPair.getPrivate());

        // 存储公钥到用户对象
        user.setPublicKey(publicKey);

        // 存储私钥到用户对象（仅作为示例，实际应用中应妥善保管私钥）
        user.setPrivateKey(privateKey);
        this.add(user);
    }

    public User login(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!dbUser.getPassword().equals(securePassword(account.getPassword()))) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbUser.getId() + "-" + RoleEnum.USER.name();
        String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
        dbUser.setToken(token);

        return dbUser;
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbUser.setPassword(securePassword(account.getNewPassword()));
        userMapper.updateById(dbUser);
    }

    private static String securePassword(String password) {
        return SecureUtil.md5(password);
    }

}